package com.totoro.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Repository;

import com.totoro.domain.User;
import com.totoro.domain.UserRole;

@Repository
public class UserRoleDao extends BaseHibernateDao<UserRole, Integer>{
	
	public UserRoleDao(){
	}
	
	// 通过用户名获得权限集合
	public Collection<GrantedAuthority> loadUserAuthorityByName(User user) {

			List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			// 角色列表
			List<String> authsList = loadUserAuthorities(user);

			for (String roleName : authsList) {
				SimpleGrantedAuthority authority = new SimpleGrantedAuthority(
						roleName);
				auths.add(authority);
			}
			return auths;

		}

		// 获取角色列表
		public List<String> loadUserAuthorities(User user) {
			Collection<UserRole> collections = this.list("user", user);
			List<String> roles = new ArrayList<String>();
			for (UserRole userRole : collections) {
				roles.add(userRole.getRole().getName());
			}
			return roles;
		}
}
